package com.wutong.authority_server.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wutong.authority_server.entity.Permission;
import com.wutong.authority_server.entity.Role;
import com.wutong.authority_server.entity.User;
import com.wutong.authority_server.mapper.PermissionMapper;
import com.wutong.authority_server.mapper.RoleMapper;
import com.wutong.authority_server.mapper.UserMapper;
import com.wutong.authority_server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-01-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    RoleMapper roleMapper;
    @Resource
    PermissionMapper permissionMapper;
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    UserMapper userMapper;

    @Override
    public User selectByUsername(String username) {
        return baseMapper.selectOne(new QueryWrapper<User>().eq("username", username));
    }

    //根据用户查询用户权限列表和角色列表
    @Override
    public List<GrantedAuthority> getUserAuthorityInfo(Integer userId) {

        User user = userMapper.selectById(userId);
        String username = user.getUsername();

        String authority = "";

        if(redisTemplate.hasKey("GrantedAuthority" + username)){
           authority =(String)redisTemplate.opsForValue().get("GrantedAuthority" + username);
        }else {
            //查询角色名称
            List<Role> roles = roleMapper.getRolesByUserId(userId);
            if(roles.size() > 0){
                String roleNames = roles.stream().map(r -> "ROLE_" + r.getRoleName()).collect(Collectors.joining(","));
                authority = roleNames.concat(",");
            }
            List<Permission> permissions = permissionMapper.selectPermissionByUserId(userId);
            if(permissions.size() > 0){
                String perValues = permissions.stream().map(p ->  p.getPermissionValue()).collect(Collectors.joining(","));
                authority = authority.concat(perValues);
            }
            redisTemplate.opsForValue().set("GrantedAuthority" + username,authority);
        }
        return  AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
